<?php

namespace common\jobs;

use Yii;
use yii\helpers\ArrayHelper;
use common\models\user\User;
use common\models\app\AppToken;

/**
 * 动态内容@用户通知任务
 * Class DynamicAtNotice
 */
class DynamicAtNoticeJob extends \yii\base\BaseObject implements \yii\queue\JobInterface {

    public $dynamic_id;
    public $uids = [];
    public $usernames = [];

    /**
     * @param \yii\queue\Queue $queue which pushed and is handling the job
     */
    public function execute($queue) {
        Yii::error('[DynamicAtNoticeJob EXECUTE]', 'queue');

        if (empty($this->uids) && empty($this->usernames)) {
            return false;
        }

        Yii::error([
            'uids' => $this->uids,
            'usernames' => $this->usernames,
        ], 'queue');

        if (!empty($this->usernames)) {
            $uids = User::find()->where(['username' => $this->usernames])->column();
            $this->uids = ArrayHelper::merge($this->uids, $uids);
        }

        Yii::error([
            'uids' => $this->uids,
        ], 'queue');

        $tokens = AppToken::find()->alias('t')->joinWith('device device')->select('push_token')->where(['t.user_id' => $this->uids])->column();

        $tokens = array_filter($tokens);

        Yii::error([
            'tokens' => $tokens,
        ], 'queue');

        Yii::error([
            'title' => '[PROD]尊敬的用户，有人在动态内容中@到您，点击查看',
            'redirect' => 'lntsfc://web?link=https://daas.lnts.cn/m/user/birthday' . $this->dynamic_id,
            'tokens' => $tokens,
        ], 'queue');

        $queue->push(new JPushJob([
            'title' => '[PROD]尊敬的用户，有人在动态内容中@到您，点击查看',
            'redirect' => 'lntsfc://web?link=https://daas.lnts.cn/m/user/birthday' . $this->dynamic_id,
            'tokens' => $tokens,
        ]));

        return true;
    }

}
